package com.inche.camerademo.Util;


import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.util.Size;

import com.inche.camerademo.Util.size.surfaceSize;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

// 这个类是用来做 相机预览画面调整的 调整具体预览画面的宽高
public class CameraPreviewAdjuster {
    public static final String TAG = "CameraPreviewAdjuster";

    public surfaceSize getSurfaceSize(CameraCharacteristics characteristics,int textureViewWidth, int textureViewHeight) {
        // 1. 从相机特性中获取「预览用的尺寸配置」
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (map == null) return null;

        // 2. 获取「相机支持输出到SurfaceTexture（预览）」的所有尺寸
        Size[] supportedSizes = map.getOutputSizes(SurfaceTexture.class);
        if (supportedSizes == null || supportedSizes.length == 0) return null;

        // 3. 筛选：找出与TextureView比例完全一致的尺寸
        List<Size> matchingRatioSizes = new ArrayList<>();
        for (Size size : supportedSizes) {
            // 用交叉相乘判断比例是否一致（避免浮点数精度问题）
            if ((long) textureViewWidth * size.getHeight() == (long) size.getWidth() * textureViewHeight) {
                matchingRatioSizes.add(size);
            }
        }

        // 4. 优先：从比例一致的尺寸中，选最大的（保证清晰度最高）
        if (!matchingRatioSizes.isEmpty()) {
            Size bestSize = Collections.max(matchingRatioSizes, (s1, s2) ->
                    Long.compare((long) s1.getWidth() * s1.getHeight(), (long) s2.getWidth() * s2.getHeight())
            );
            return new surfaceSize(bestSize.getWidth(), bestSize.getHeight());
        }

        // 5. 补救：如果没有完全匹配的比例，选最接近的尺寸（最小化拉伸）
        float targetRatio = (float) textureViewWidth / textureViewHeight;
        float minDiff = Float.MAX_VALUE;
        Size bestApproximateSize = null;

        for (Size size : supportedSizes) {
            float currentRatio = (float) size.getWidth() / size.getHeight();
            float diff = Math.abs(currentRatio - targetRatio); // 计算比例差值

            // 规则：差值越小越好；差值相同时，尺寸越大越好（清晰度更高）
            if (diff < minDiff || (diff == minDiff && bestApproximateSize != null && size.getWidth() > bestApproximateSize.getWidth())) {
                minDiff = diff;
                bestApproximateSize = size;
            }
        }

        // 6. 返回最佳近似尺寸（如果找到的话）
        if (bestApproximateSize != null) {
            return new surfaceSize(bestApproximateSize.getWidth(), bestApproximateSize.getHeight());
        }

        // 7. 终极 fallback：所有努力都失败，返回null
        return null;
    }

}


